package mypackage.forfun;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

public class WebkitDemo extends Activity {
	WebView browser;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		browser = (WebView) findViewById(R.id.webview);
		browser.loadUrl("http://www2.leboncoin.fr/ar/form/0?ca=15_s&id=328084729");

		// not working....
		// browser.loadDataWithBaseURL("file:///android_asset/page.html",
		// null,"text/html", "utf-8", null);
		/*
		try {
			
			  String textFromCSS=getTextFromRessourceId(R.raw.css);
			  
			  HashMap<String, String> map=new HashMap<String, String>();
			 map.put("style", textFromCSS);
			  
			  String
			  textFromPage=getTextFromRessourceWithValues(R.raw.page,map);
			 
			browser.getSettings().setJavaScriptEnabled(true);
			String textFromPage = getTextFromRessourceId(R.raw.form);
			browser.loadData(textFromPage, "text/html", "UTF-8");

		} catch (IOException e1) {
			e1.printStackTrace();
		}
		*/

	}

	public String getTextFromRessourceWithValues(int idRessource,
			HashMap<String, String> map) throws IOException {
		return replaceValuesFromMapAndText(getTextFromRessourceId(idRessource),
				map);
	}

	public String replaceValuesFromMapAndText(String sources,
			HashMap<String, String> map) {

		Iterator<String> keys = map.keySet().iterator();

		String key = "";

		while (keys.hasNext()) {
			key = keys.next();
			sources = sources.replace("${" + key + "}", map.get(key));
		}

		return sources;
	}

	public String getTextFromRessourceId(int idRessource) throws IOException {
		InputStream inputStream = getResources().openRawResource(idRessource);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int i = inputStream.read();
		while (i != -1) {
			byteArrayOutputStream.write(i);
			i = inputStream.read();
		}
		inputStream.close();
		return byteArrayOutputStream.toString();
	}

	public void push(View view) {
		browser.loadUrl("javascript:submitform()");
	}
}